package com.ruoyi.util;

import com.ruoyi.basebill.mapper.BillUtilMapper;
import com.ruoyi.basedocument.domain.BomFileattstor;
import com.ruoyi.basedocument.mapper.BomFileattstorMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Component
public class BillUtil {

    @Autowired
    private BillUtilMapper billUtilMapper;

    @Autowired
    private BomFileattstorMapper fileattstorMapper;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 根据传入的表名，生成对应的单据的编码
     *
     * @param str       单据编号开头
     * @param tableName 表名
     */
    public synchronized String createBillNumber(String str, String tableName) {
        //时间字符串产生方式
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        //组合流水号前一部分
        String billNumberPfix = format.format(nowDate);
        ArrayList<String> strArr = new ArrayList();
        List list = Arrays.asList("CBCS", "CSXQ");
        strArr.addAll(list);
        if (strArr.contains(str)) {
            billNumberPfix = str + "-" + billNumberPfix;
        }
        String formerBillNumber;
        //获取指定单据的最新一条记录的编码
        formerBillNumber = billUtilMapper.getNewNumber(billNumberPfix, tableName);
        //最终的单据编号
        String commentNumber = "";
        //判断数据库中是否存在数据
        if (formerBillNumber != null && formerBillNumber.contains(billNumberPfix)) {
            //从单据编号中截取后6位
            String billNumberEnd = formerBillNumber.substring(formerBillNumber.length() - 5);
            int endNumber = Integer.parseInt(billNumberEnd);
            int tempNumber = 100000 + endNumber + 1;
            //将首位的1去掉之后，拼接成流水号
            if (strArr.contains(str)) {
                commentNumber = billNumberPfix + '-' + String.valueOf(tempNumber).substring(1);
            } else {
                commentNumber = str + '-' + billNumberPfix + '-' + String.valueOf(tempNumber).substring(1);
            }
        } else {
            //当数据库中没有数据时
            if (strArr.contains(str)) {
                commentNumber = billNumberPfix + '-' + "00001";
            } else {
                commentNumber = str + '-' + billNumberPfix + '-' + "00001";
            }
        }

        return commentNumber;
    }

    /**
     * 格式化税率
     *
     * @param taxrate 传入的bigdecimal对象
     * @return 格式化好的税率数据
     */
    public static BigDecimal formatTaxRate(BigDecimal taxrate) {
        if (StringUtils.isNull(taxrate)) {
            return null;
        }
        if (taxrate.compareTo(new BigDecimal(1)) > -1) {
            BigDecimal divide = taxrate.divide(new BigDecimal(100), 6, RoundingMode.HALF_UP);
            return divide;
        }
        return taxrate;
    }


    /**
     * 将Date转换成LocalDate
     *
     * @param date
     * @return
     */
    public static LocalDate convertDateToLocalDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        LocalDate localDate = LocalDate.of(year, month, day);
        return localDate;
    }


    /**
     * 将LocalDate转换成Date
     *
     * @param localDate
     * @return
     */
    public static Date convertLocalDateToDate(LocalDate localDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth());
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        try {
            date = sdf.parse(format);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }

    public static String getDictLabel(String dictType){
        List<SysDictData> bom_wfzbase = DictUtils.getDictCache(dictType);
        String strings = "";
        for (int i = 0; i < bom_wfzbase.size(); i++) {
            String dictLabel = bom_wfzbase.get(i).getDictLabel();
            strings += ","+dictLabel;
        }
        return strings;
    }

    public void insertFile(String attachmeet,String id) {
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        BomFileattstor fileattstor1 = new BomFileattstor();
        fileattstor1.setSourceid(id);
        List<BomFileattstor> fileattstors = fileattstorMapper.selectBomFileattstorList(fileattstor1);
        for (int i = 0; i < fileattstors.size(); i++) {
            BomFileattstor bomFileattstor = fileattstors.get(i);
            String filepath1 = bomFileattstor.getFilepath();
            if(!attachmeet.contains(filepath1)){
                String filepath = localPath+ filepath1.substring(8);
                FileUtils.deleteFile(filepath);
            }
            fileattstorMapper.deleteBomFileattstorById(bomFileattstor.getId());
        }
        if (StringUtils.isNotBlank(attachmeet)) {
            String[] split = attachmeet.split(",");
            for (String path : split) {
                BomFileattstor fileattstor = new BomFileattstor();
                fileattstor.setSourceid(id);
                fileattstor.setFilepath(path);
                fileattstor.setFilename(fileattstor.getFileNameUtil(path));
                fileattstor.setFiletype(fileattstor.getFileTypeUtil(path));
                fileattstorMapper.insertBomFileattstor(fileattstor);
            }
        }

    }

    public String selectFile(String id) {
        BomFileattstor fileattstor = new BomFileattstor();
        fileattstor.setSourceid(id);
        List<BomFileattstor> fileattstors = fileattstorMapper.selectBomFileattstorList(fileattstor);
        String path = "";
        for (int i = 0; i < fileattstors.size(); i++) {
            if (i == fileattstors.size() - 1) {
                path += fileattstors.get(i).getFilepath();
            } else {
                path += fileattstors.get(i).getFilepath() + ",";
            }
        }
        return path;
    }

}
